package algorithm

import (
	"github.com/bgmp/config"
	"github.com/bgmp/handler"
	"github.com/bgmp/middleware"
	"github.com/bgmp/model"
	"github.com/bgmp/service"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
)

func (b Base) Prescription(c *gin.Context, req *PrescriptionRequest) *PrescriptionResponse {
	userId := middleware.GetUserId(c)
	if req.PatientId != 0 {
		userId = req.PatientId
	}
	log.Info("now userid is ", userId)

	bgs := model.GetBgBefore(config.DB, userId, req.Time, 96)

	if len(bgs) == 0 {
		return &PrescriptionResponse{
			PrescriptionResult: service.PrescriptionResult{
				Prescription: "decrease",
			},
		}
	}
	detail := &model.UserDetail{}
	detail.UserId = userId
	if err := detail.GetByUserId(config.DB); err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}

	extra := transformExtra(detail)
	t := &model.InsulinTherapy{
		UserId: req.PatientId,
	}
	err := t.GetBefore(config.DB, req.Time)

	log.Info("bgs' length is ", len(bgs))

	result, err := service.Prescription(bgs, extra, t)
	if err != nil {
		handler.Errorf(c, err.Error())
		return nil
	}
	return &PrescriptionResponse{
		PrescriptionResult: *result,
	}
}

type PrescriptionRequest struct {
	Time      model.Time `json:"time"`
	PatientId uint       `json:"patient_id"`
}

type PrescriptionResponse struct {
	service.PrescriptionResult
}
